/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUITook.java
 *
 * Created on 29/10/2010, 00:18:52
 */
package ifpb.pod.cliente.visao;

import ifpb.pod.cliente.funcionalidades.ClienteRemotoImpl;
import ifpb.pod.cliente.funcionalidades.FachadaCliente;
import ifpb.pod.model.Contato;
import ifpb.pod.model.Noticia;
import ifpb.pod.model.Usuario;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;

/**
 *
 * @author Diogenes
 */
public class GUITook extends javax.swing.JFrame {

    /** Creates new form GUITook */
    private DefaultListModel listaOn;
    private DefaultListModel listaOff;
    private DefaultListModel modelContatos;
    private DefaultListModel modelContatosNoticia;
    private ClienteRemotoImpl cliente;
    private FachadaCliente fachada;
    private Usuario usuario;

    public GUITook(Usuario usuario) {
        initComponents();
        this.inicalizaListas();
        this.fachada = FachadaCliente.getInstance();
        setUsuario(usuario);
        Contato contatoDoUsuario = new Contato(usuario.getContaUsuario().getLogin());
        try {
            this.cliente = new ClienteRemotoImpl(contatoDoUsuario);
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }

        inicializaModelListaEnviar();
    }

    private void inicalizaListas() {
        listaOn = new DefaultListModel();
        this.lContatosOn.setModel(listaOn);
        listaOff = new DefaultListModel();
        this.lContatosOff.setModel(listaOff);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        lContatosOn = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        lContatosOff = new javax.swing.JList();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        listaNoticias = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        listaHistoricoNotificacoes = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        areaNoticia = new javax.swing.JTextArea();
        bEnviar = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        listaContatosNoticia = new javax.swing.JList();
        jToolBar1 = new javax.swing.JToolBar();
        btAdd = new javax.swing.JButton();
        iUsuario = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        iDesconectar = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        iSair = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane2.setOpaque(false);

        lContatosOn.setBorder(javax.swing.BorderFactory.createTitledBorder("Contatos ON"));
        lContatosOn.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lContatosOn.setOpaque(false);
        lContatosOn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lContatosOnMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(lContatosOn);

        jScrollPane2.setBounds(10, 10, 200, 210);
        jLayeredPane1.add(jScrollPane2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPane1.setOpaque(false);

        lContatosOff.setBorder(javax.swing.BorderFactory.createTitledBorder("Contatos OFF"));
        lContatosOff.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lContatosOff.setOpaque(false);
        lContatosOff.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lContatosOffMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lContatosOff);

        jScrollPane1.setBounds(10, 230, 200, 220);
        jLayeredPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        listaNoticias.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listaNoticias.setOpaque(false);
        jScrollPane5.setViewportView(listaNoticias);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Notícias", jPanel2);

        listaHistoricoNotificacoes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listaHistoricoNotificacoes.setOpaque(false);
        jScrollPane6.setViewportView(listaHistoricoNotificacoes);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Histórico de Notificações", jPanel1);

        jTabbedPane1.setBounds(220, 170, 460, 280);
        jLayeredPane1.add(jTabbedPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        areaNoticia.setColumns(20);
        areaNoticia.setLineWrap(true);
        areaNoticia.setRows(5);
        areaNoticia.setWrapStyleWord(true);
        areaNoticia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                areaNoticiaKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(areaNoticia);

        jScrollPane3.setBounds(220, 10, 460, 110);
        jLayeredPane1.add(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        bEnviar.setText("Enviar");
        bEnviar.setEnabled(false);
        bEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bEnviarActionPerformed(evt);
            }
        });
        bEnviar.setBounds(610, 130, 63, 30);
        jLayeredPane1.add(bEnviar, javax.swing.JLayeredPane.DEFAULT_LAYER);

        listaContatosNoticia.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listaContatosNoticia.setOpaque(false);
        listaContatosNoticia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaContatosNoticiaMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(listaContatosNoticia);

        jScrollPane4.setBounds(220, 130, 380, 30);
        jLayeredPane1.add(jScrollPane4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        btAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ifpb/pod/cliente/icones/add.png"))); // NOI18N
        btAdd.setFocusable(false);
        btAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });
        jToolBar1.add(btAdd);

        iUsuario.setText("Usuario");
        jToolBar1.add(iUsuario);

        jMenu1.setText("Arquivo");

        iDesconectar.setText("Desconectar");
        iDesconectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                iDesconectarActionPerformed(evt);
            }
        });
        jMenu1.add(iDesconectar);
        jMenu1.add(jSeparator1);

        iSair.setText("Sair");
        iSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                iSairActionPerformed(evt);
            }
        });
        jMenu1.add(iSair);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE)
            .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-704)/2, (screenSize.height-558)/2, 704, 558);
    }// </editor-fold>//GEN-END:initComponents

    private void iSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_iSairActionPerformed
        this.dispose();
        desautenticar();
    }//GEN-LAST:event_iSairActionPerformed

    private void iDesconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_iDesconectarActionPerformed
        this.dispose();
        desautenticar();
        new GUILogin().setVisible(true);
    }//GEN-LAST:event_iDesconectarActionPerformed

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        String login = JOptionPane.showInputDialog("Digite o login do contato");
        if (!(login == null || login.trim().isEmpty())) {
            setUsuario(this.fachada.addAmigoContato(this.usuario, login));
        }
    }//GEN-LAST:event_btAddActionPerformed

    private void lContatosOnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lContatosOnMouseClicked
        this.lContatosOff.clearSelection();
        doubleClick(evt);
    }//GEN-LAST:event_lContatosOnMouseClicked

    private void lContatosOffMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lContatosOffMouseClicked
        this.lContatosOn.clearSelection();
        doubleClick(evt);
    }//GEN-LAST:event_lContatosOffMouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        desautenticar();
    }//GEN-LAST:event_formWindowClosing

    private void areaNoticiaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_areaNoticiaKeyPressed
        areaNoticia.requestFocus();
        if (areaNoticia.getText().equals("")) {
            bEnviar.setEnabled(false);
        } else {
            bEnviar.setEnabled(true);
        }
    }//GEN-LAST:event_areaNoticiaKeyPressed

    private void listaContatosNoticiaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaContatosNoticiaMouseClicked
        if (evt.getClickCount() == 2) {
            new GUISeletorContatos(this.modelContatos, this.modelContatosNoticia).setVisible(true);
        }
    }//GEN-LAST:event_listaContatosNoticiaMouseClicked

    private void bEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bEnviarActionPerformed
        Object[] contatos = modelContatosNoticia.toArray();
        if (contatos.length > 0) {
            String conteudo = areaNoticia.getText();
            if (!conteudo.trim().equals("")) {
                Noticia noticia = new Noticia(new Contato(this.usuario.getContaUsuario().getLogin()), conteudo);
//                Noticia noticia = new Noticia(this.usuario.getContaUsuario().getLogin()+conteudo);
                System.out.println(noticia);
                try {
                    cliente.enviarNoticia(noticia, toListContatos(contatos));
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                }
                System.out.println("Enviou");
                inicializaModelListaEnviar();
                limpaNoticia();
            }

        } else {
            JOptionPane.showMessageDialog(null, "Adicione remetente(s)");
        }


    }//GEN-LAST:event_bEnviarActionPerformed

    private List<Contato> toListContatos(Object[] array) {
        List<Contato> contatos = new ArrayList<Contato>();
        for (Object contato : Arrays.asList(array)) {
            contatos.add((Contato) contato);
        }
        return contatos;
    }

    public void notificarNoticiaChegou() {
        atualizaUsuario(usuario);
        JOptionPane.showMessageDialog(null, "Chegou notícia");
    }

    private void desautenticar() {
        this.fachada.desautenticar(this.usuario.getContaUsuario());
    }

    private void doubleClick(MouseEvent evt) {
        if (evt.getClickCount() == 2) {
            Contato remetente = new Contato(this.usuario.getContaUsuario().getLogin());
            JList listaclicada = (JList) evt.getSource();
            Contato destinatario = new Contato((String) listaclicada.getSelectedValue());
            try {
                cliente.solicitarConversa(destinatario);
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void addContatosOnline(String nikUsuario) {
        listaOn.addElement(nikUsuario);
    }

    public void addContatosOffline(String nikUsuario) {
        listaOff.addElement(nikUsuario);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea areaNoticia;
    private javax.swing.JButton bEnviar;
    private javax.swing.JButton btAdd;
    private javax.swing.JMenuItem iDesconectar;
    private javax.swing.JMenuItem iSair;
    private javax.swing.JLabel iUsuario;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JList lContatosOff;
    private javax.swing.JList lContatosOn;
    private javax.swing.JList listaContatosNoticia;
    private javax.swing.JList listaHistoricoNotificacoes;
    private javax.swing.JList listaNoticias;
    // End of variables declaration//GEN-END:variables

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
        this.setTitle("Took - " + usuario.getNome());
        this.iUsuario.setText(usuario.getNome());
        preencheLista();
        preencheListaNoticia();
        System.out.println("verificar ainda porque coloquei isso embaixo, acho que só vai ser util quando add algqum amigo");
        inicializaModelListaEnviar();
    }

    private void preencheLista() {
        //preenchendo lista on
        this.listaOn.removeAllElements();
        List<Contato> contatosOnline = new ArrayList<Contato>();
        contatosOnline = fachada.getAmigosOnline(usuario);
        System.out.println(contatosOnline.size() + "onlineeee");
        Collections.sort(contatosOnline);
        for (Contato amigo : contatosOnline) {
            System.out.println(amigo.getLogin() + "");
            addContatosOnline(amigo.getLogin());
        }
        //preenchendo lista off
        this.listaOff.removeAllElements();
        List<Contato> contatosOffLine = new ArrayList<Contato>();
        contatosOffLine.addAll(usuario.getContatos());
        Collections.sort(contatosOffLine);
        contatosOffLine.removeAll(contatosOnline);
        for (Contato amigo : contatosOffLine) {
            addContatosOffline(amigo.getLogin());
        }

    }

    public void amigFoEntrou(Contato contato) {
        listaOn.addElement(contato.getLogin());
    }

    public void atualizaUsuario(Usuario usuario) {
        System.out.println(usuario.getNome() + "olalalala");
        setUsuario(usuario);
    }

    public Usuario getUsuario() {
        return this.usuario;
    }

    private void inicializaModelListaEnviar() {
        this.modelContatos = new DefaultListModel();
//       inicializaModelListaEnviar();
        this.modelContatosNoticia = new DefaultListModel();
        this.listaContatosNoticia.setModel(modelContatosNoticia);


//         Collections.sort(contatos);
        for (Contato contato : this.usuario.getContatos()) {
            this.modelContatos.addElement(contato);
        }

    }

    private void limpaNoticia() {
        this.areaNoticia.setText(null);
        this.areaNoticia.requestFocus();
    }

    private void preencheListaNoticia() {
        DefaultListModel modelNoticia = new DefaultListModel();
        listaNoticias.setModel(modelNoticia);
        List<Noticia> noticias = fachada.getNoticias(usuario);
        if (noticias != null) {
            for (Noticia noticia : noticias) {
                modelNoticia.addElement(noticia);
            }
        }

    }
}
